package cn.ctyun.ipush.utils;

import cn.ctyun.ipush.constant.ResultInfo;
import cn.ctyun.ipush.dto.ResultDto;
import cn.ctyun.ipush.model.TaskDetailModel;
import com.aspose.cells.DateTime;
import org.apache.commons.lang.StringUtils;
import org.quartz.CronTrigger;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: user
 * Date: 16-6-14
 * Time: 下午2:50
 * To change this template use File | Settings | File Templates.
 */
public class DateUtils {

    /**
     * 将java.util.Date 格式转换为字符串格式'yyyy-MM-dd HH:mm:ss a'(12小时制)<br>
     * 如Sat May 11 17:23:22 CST 2002 to '2002-05-11 05:23:22 下午'<br>
     * @param time Date 日期<br>
     * @return String 字符串<br>
     */
    public static String dateToString(Date time){
        SimpleDateFormat formatter;
        formatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss ");
        String ctime = formatter.format(time);
        return ctime;
    }


    /**
     * 将时间戳（精确到毫秒）转换成日期格式字符串
     * @param time
     * @return
     */
    public static String timestampToDataString(long time){
        Timestamp ts = new Timestamp(time);
        String tsStr = "";
        DateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        return sdf.format(ts);
    }

    //  加锁实现某个时间点只有一个线程访问，保证hashmap的一致性
    public synchronized static ResultDto isCronNoExistAndIsLegal(List<TaskDetailModel> taskDetailModelList,String cronTrigger){
        ResultDto resultDto=new ResultDto();
        //空的话 还没有任务
        if(taskDetailModelList==null || taskDetailModelList.size()<1){
            resultDto.setStatus(ResultInfo.success);
            return resultDto;
        }
        List<String> cronList=new ArrayList<String>();
        for (TaskDetailModel taskDetailModel:taskDetailModelList){
            String cron=taskDetailModel.getCronExpression();
            if(!StringUtils.isEmpty(cron)){
                String[] cronStrs=cron.split("@");
                for(String cronStr:cronStrs){
                    cronList.add(cronStr.trim());
                }
            }
        }
        //isExist
        String[]  times=cronTrigger.trim().split("\\s+");
        for(String cron:cronList){
            String[] dbTimes=cron.trim().split("\\s+");
            if(Arrays.equals(times, dbTimes)){
                resultDto.setStatus(ResultInfo.failure);
                resultDto.setInfo("执行时间已经在系统中已有任务中存在，请修改执行时间");
                return resultDto;
            }
        }
        //isLegal
        for(String cron:cronList){
            String[] dbTimes=cron.trim().split("\\s+");
            String[] dbTimesTmp=new String[]{dbTimes[3],dbTimes[4],dbTimes[5]};
            String[] timesTmp=new String[]{times[3],times[4],times[5]};
            if(Arrays.equals(dbTimesTmp, timesTmp)){
               int dbMinutes=Integer.parseInt(dbTimes[0])+60*Integer.parseInt(dbTimes[1])+3600*Integer.parseInt(dbTimes[2]);
               int minutes=Integer.parseInt(times[0])+60*Integer.parseInt(times[1])+3600*Integer.parseInt(times[2]);
               if(Math.abs(dbMinutes-minutes)<180){
                   resultDto.setStatus(ResultInfo.failure);
                   resultDto.setInfo("执行时间与系统中已有任务的执行时间差值小于180秒，请修改执行时间");
                   return resultDto;
               }
            }
        }
        resultDto.setStatus(ResultInfo.success);
        return resultDto;
    }

    public static String getWeekStartDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        Date date = cal.getTime();
        return sdf.format(date);
    }

    public static  String getWeekLastDay(String date){
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Date dt= null;
        try {
            dt = sdf.parse(date);
            Calendar rightNow = Calendar.getInstance();
            rightNow.setTime(dt);
            rightNow.add(Calendar.DAY_OF_YEAR,6);//日期加6天
            Date dt1=rightNow.getTime();
            String reStr = sdf.format(dt1);
            return reStr;
        } catch (ParseException e) {
            return null;
        }


    }
}
